var app = getApp()
import Poster from '../../poster-plugin/poster/poster';
const posterConfig = require('../../config/poster.js');
var util = require('../../utils/util.js')
var base64 = require('../../utils/base64.js')
const date_util = require('../../utils/date_util.js')
var api = require('../../config/api.js')
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const posterFeelingConfig = posterConfig.getPosterFeelingCinfig();
const picIcon = [
  'https://qn.simullink.com/FocVsylregOdmd8KFxagoOfkGa4y', 'https://qn.simullink.com/Fj1Bo9ne1iL9_c9FH86dUXqJMpe5',
  'https://qn.simullink.com/Fr1L8X6UPxcBOydhVSHD3sEniuWC', 'https://qn.simullink.com/Fr1L8X6UPxcBOydhVSHD3sEniuWC'];

Page({
  data: {
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    id: 0,
    item: null,
    myfollowacts: [],
    uuid: '',
    title: '',
    pic: '',
    source: 'detail',
    activityInfo: {},
    phValue: '表达感受...',
    comment_content: '',
    commentflag: false,
    commentId: '',
    source: '',
    userInfo: app.globalData.userInfo,
    auth: app.globalData.auth,
    systemInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    hasPhone: app.globalData.hasPhone,
    // 父评论相关参数
    fatherComments: [],
    newFaList: [],
    fatherPage: 1,
    fatherSize: 100,
    // 子评论相关参数
    sonComments: [],
    sonPage: 1,
    sonSize: 20,
    comment: [],
    fatherCommentsisEmpty: false,
    hiddenDelete: true,
    hiddenAll: true,
    hiddenShare: true,
    hiddenNavigation: true,
    hiddenWxShare: true,
    sharepicurl: '',
    shareImg: '',
    shareindex: 0,
    direction: 'heng',
    //处理视频
    noPageScroll: false,
    videoContext: null,
    isPlay: true,
    marginWidth:0
  },


  //视频播放与暂停
  // 点击播放按钮
  play: function() {
    if (this.data.isPlay) {
      this.setData({
        isPlay: false,
        commentflag: false,
        hiddenDelete: true,
      })
      this.videoContext.pause();
    } else {
      this.setData({
        isPlay: true,
        commentflag: false,
        hiddenDelete: true,
      })
      this.videoContext.play()
      // this.videoContext.requestFullScreen();
    }
  },

  // 开始播放
  bindPlay: function() {
    this.setData({
      isPlay: true
    })
  },

  // 暂停播放
  bindPause: function() {
    this.setData({
      isPlay: false
    })
  },

  // 播放完毕
  bindEnded: function() {
    this.setData({
      isPlay: false
    })
  },
  //视频时间更新
  timeupdate: function(e) {},

  //新版改造
  onLoad: function(options) {
    var that = this;
    wx.hideShareMenu();
    let dataEncode = options.dataObj
    let uuid = options.uuid
    let title = options.title
    let pic = options.pic
    var direction = options.direction
    if (direction == "undefined") {
      direction = 'heng'
    }
    let source = options.source
    let dataDecode = decodeURIComponent(dataEncode)
    let item = JSON.parse(base64.decode(dataDecode))

    if (item.media && item.media.length > 0) {
      item.videoPath = item.media[0].url
    }

    wx.showShareMenu({
      withShareTicket: true
    });

    that.setData({
      item: item,
      uuid: uuid,
      title: title,
      direction: direction,
      pic: pic,
      source: source,
      userInfo: app.globalData.userInfo,
      hasUserInfo: app.globalData.hasUserInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
      isPlay: false
    });

    wx.getSystemInfo({
      success: function(res) {
        let w = res.windowWidth,
          h = res.windowHeight;
        that.setData({
          winWidth: w,
          winHeight: h,
          systemInfo: res,
          marginWidth: (res.windowWidth - 166) / 2,
          videoHengLocation: (h-225)/2
        })
      },
    })
  },

  onMyevent: function(e) {
    var that = this
    that.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
  },
  launchAppError: function(e) {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },
  onReady: function() {
    this.videoContext = wx.createVideoContext('myVideo')
    this.setData({
      isPlay: true
    })
  },
  onShow: function() {
    this.setData({
      userInfo: app.globalData.userInfo,
      hasUserInfo: app.globalData.hasUserInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
    });
  },
  onHide: function() {

  },

  backhome: function() {
    if (this.data.source == 'detail') {
      wx.navigateBack({
        delta: 1
      })
    }

    if (this.data.source == 'app') {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }

  },

  tongGan: function(e) {
    let index = e.currentTarget.dataset.index
    var that = this
    let count = that.data.item.simul_count
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan, 'POST', {
        activityId: that.data.item.activityId,
        feelingId: that.data.item.id
      }).then(res => {
        if (res && res.code == 200) {
          var ttItem = that.data.item
          ttItem.currentUserCollected = true
          ttItem.simul_count = count + 1
          this.setData({
            item: ttItem
          })
          wx.showToast({
            title: '深有同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }
  },


  feelingFirstLineLocation: function (type, avatarUrl, nickname, viplevel, emoji) {
    posterFeelingConfig[type + 'Config'].images = []
    posterFeelingConfig[type + 'Config'].texts = []
    let len = 15,
      textStart = 120,
      jiange = 15;
    let textWidth = util.getTextLength(nickname) * len;
    posterFeelingConfig[type + 'Config'].images.push({
      width: 80,
      height: 80,
      x: 20,
      y: 30,
      borderRadius: 80,
      url: avatarUrl,
    })
    posterFeelingConfig[type + 'Config'].texts.push({
      x: textStart,
      y: 70,
      baseLine: 'middle',
      text: nickname,
      width: textWidth,
      fontSize: 32,
      color: '#000000',
    })
    if (viplevel > 0) {
      let kolStart = textStart + textWidth + jiange;
      posterFeelingConfig[type + 'Config'].images.push({
        width: 24,
        height: 24,
        x: kolStart,
        y: 58,
        borderRadius: 24,
        url: '',
      })
    }
    if (emoji) {
      let gandaoStart = textStart + textWidth + jiange;
      if (viplevel > 0) {
        gandaoStart = gandaoStart + 24 + jiange;
      }
      posterFeelingConfig[type + 'Config'].texts.push({ //感到
        x: gandaoStart,
        y: 70,
        baseLine: 'middle',
        text: '感到',
        width: 40,
        fontSize: 32,
        color: '#FF0000',
      })
      posterFeelingConfig[type + 'Config'].texts.push({ //表情
        x: gandaoStart + 60 + jiange,
        y: 70,
        baseLine: 'middle',
        text: emoji,
        fontSize: 32,
        color: '#000000',
      })
    }

  },


  // 分享视频
  updateFeelingPosterConfig: function(feeling, qrcode) { //picIcon数组  feeling一条感受对象  qrcode二维码图片url
    this.feelingFirstLineLocation(feeling.type, feeling.user.avatarUrl, feeling.user.nickname, feeling.user.vipLevel, feeling.emotion)

    if (feeling.type == 'VIDEO') {
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.VIDEOConfig.images[1].url = picIcon[0]
      }
     
      posterFeelingConfig.VIDEOConfig.images.push({
        width: 630,
        height: 700,
        x: 20,
        y: 123,
        borderRadius: 40,
        url: feeling.thumbnail,
      })

      posterFeelingConfig.VIDEOConfig.texts.push({
        x: 20,
        y: 865,
        baseLine: 'left',
        text: feeling.content,
        width: 600,
        fontSize: 32,
        color: '#000000',
        zIndex: 100,
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //play标记
        width: 50,
        height: 50,
        x: 320,
        y: 470,
        borderRadius: 50,
        url: picIcon[1],
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //二维码
        width: 100,
        height: 100,
        x: 292,
        y: 940,
        borderRadius: 100,
        url: qrcode,
      })
    }

  },

  sharePic: function() {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        hiddenAll: false,
        hiddenNavigation: false,
        sharepicurl: '',
        isPlay:false
      })
    } else {
      that.auth.showAuth()
    }
  },

  close_share: function(e) {
    this.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      hiddenAll: true,
      isPlay: true,
      sharepicurl: ''
    })
  },

  generatePoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: true
    })
  },
  saveWX: function() {
    var that = this
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  generateWXPoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  getSharePoster: function() {
    let that = this
    let type = 'FEELING'
    var activityOrFeeling = that.data.item
    wx.showLoading({
      title: '生成海报...',
      mask: true,
    })
    util.pututrequest(api.generateQrcode, 'POST', {
      id: activityOrFeeling.id,
      type: type
    }).then(res => {
      if (res && res.code == 200) {
        let qrcode = res.data.url
        if (qrcode) {
          if (type == 'FEELING') {
            that.updateFeelingPosterConfig(activityOrFeeling, qrcode)
            this.setData({
              posterSendConfig: posterFeelingConfig['VIDEOConfig']
            }, () => {
              Poster.create(true); // 入参：true为抹掉重新生成 
            });
          }

        } else {
          wx.showModal({
            title: '二维码获取失败',
            showCancel: false,
            content: '该活动海报的二维码获取失败,请重新生成！'
          })
        }

      }
    });
  },

  onPosterSuccess(e) {
    const {
      detail
    } = e;
    this.setData({
      hiddenShare: false,
      sharepicurl: detail
    })
    wx.hideLoading()
  },
  onPosterFail(err) {
    console.error(err);
  },

  maskmove: function() {

  },
  cancleMask: function() {
    this.setData({
      commentflag: false,
      hiddenDelete: true,
      simulflag: false,
      showUpload: true,
      hiddenAll: true,
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true
    })
  },

  saveNetPicToLocal: function() {
    let that = this
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    //图片保存到本地
    wx.saveImageToPhotosAlbum({
      filePath: that.data.sharepicurl,
      success: function(data) {
        wx.showModal({
          title: '保存成功',
          content: '活动海报保存到相册成功',
          confirmText: "我知道了",
          showCancel: false,
        })
      },
      fail: function(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '授权成功，继续保存',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: '未授权，无法保存',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      },
    })
    wx.hideLoading()
  },

  onShareAppMessage: function(ops) {

    var shareText = ""
    if (this.data.item.content && this.data.item.content != '') {
      shareText = this.data.item.content
    } else {
      shareText = this.data.title
    }

    if (ops.from === 'button') { //页面内转发按钮  
    } else {

    }
    //分享评论
    return {
      title: shareText,
      desc: shareText,
      path: '/pages/detail/detail?uuid=' + this.data.uuid + '&source=app&commId=' + this.data.item.id + '&type=1',
      imageUrl: this.data.sharepicurl,
      // imageUrl:this.data.item.images_new[0].url,
      success: function(res) { // 转发成功       
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        //可以获取群组信息
        if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function(res) {
              wx.showToast({
                title: "分享成功",
                duration: 2000
              });
            },
            fail: function() {
              wx.showToast({
                title: "分享失败",
                duration: 2000
              });
            }
          })
        }
        if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
          wx.showToast({
            title: "分享成功",
            duration: 2000
          });
        }
      },
      fail: function(res) { // 转发失败        
        wx.showToast({
          title: "分享失败，请重新分享",
          duration: 2000
        });
      }
    }
  },

  videoTip: function() {
    wx.showModal({
      title: '友情提示',
      content: '想看完整视频，请下载同感App',
      confirmText: "我知道了",
      showCancel: false,
    })
  },

  changeTxtHeight: function(e) {
    var that = this;
    var item = that.data.item
    if (item.txtheight == 'txt_normal') {
      item.txtheight = 'txt_all'
    } else {
      item.txtheight = 'txt_normal'
    }
    that.setData({
      item: item
    })
  },


  //2. 获取子评论
  getComments: function(e) {
    var that = this;
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        isPlay: false
      })

      that.setData({
        comment: [],
      })
      util.pututrequest(api.commentList + '?feelingId=' + that.data.item.id + '&activityId=' + that.data.item.activityId, 'GET').then((res) => {
        if (res && res.code == 200) {
          this.setData({
            commentflag: true,
          })
          var tt = null;
          if (res.data) {
            tt = res.data.comments
          }
          if (tt) {
            for (let i = 0; i < tt.length; i++) {
              tt[i].to_now = date_util.getToNow(tt[i].createTime)
              if (tt[i].user) {
                if (tt[i].user.avatarUrl) {
                  tt[i].user.photo = tt[i].user.avatarUrl
                } else {
                  tt[i].user.photo = 'http://simul.dpaper.cn/miniprogram/images/index/photo.jpeg'
                }
              }
              this.setData({
                comment: tt,
              })
            }
          }
        }

      })
    } else {
      that.auth.showAuth()
    }
  },
  // 2.1 评论框焦点
  onFocus: function(e) {
    this.setData({
      phValue: " "
    })
  },
  // 2.2 评论框失去焦点
  onBlur: function(e) {
    this.setData({})
  },
  // 2.3 评论框输入
  commentInput: function(e) {
    this.setData({
      comment_content: e.detail.value
    })
  },
  // 2.4 发送子评论
  sendComment: function(e) {
    var that = this;
    var count = that.data.item.comment_count
    var comm = e.currentTarget.dataset.comm
    if (comm == '' || comm == null) {
      wx.showToast({
        title: '请输入评论内容!',
        icon: 'success',
        duration: 2000
      })
      return;
    }
    var commArry = []
    if (that.data.comment.length > 0) {
      commArry = that.data.comment
      commArry.unshift({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": app.globalData.userInfo.avatarUrl
        },
        "content": comm
      })
    } else {
      commArry.push({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": app.globalData.userInfo.avatarUrl
        },
        "content": comm
      })
    }

    this.setData({
      comment: commArry,
    })
    util.pututrequest(api.comment, 'POST', {
      feelingId: that.data.item.id,
      content: comm,
      activityId: that.data.item.activityId
    }).then((res) => {
      if (res && res.code == 200) {
        var tt = 'item.comment_count'
        wx.showToast({
          title: '评论成功!',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          phValue: "表达感受...",
          comment_content: '',
          [tt]: count + 1
        })
      }
    })
  },
  maskmove: function() {

  },

  click_blank: function(e) {
    this.setData({
      commentflag: false,
      hiddenShare: true,
    })
  },
  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },


  deleteComment: function (e) {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        hiddenDelete: false
      })
    } else {
      that.auth.showAuth();
    }
  },
  deleteFeeling: function () {
    var that = this
    let ffeelinga = that.data.item
    wx.showModal({
      title: '删除感受',
      content: '您确定删除这条感受吗？',
      showCancel: true, //是否显示取消按钮
      cancelText: "取消", //默认是“取消”
      cancelColor: '#0000FF',
      confirmText: "确定",
      confirmColor: '#DC143C', //确定文字的颜色
      success: function (ress) {
        if (ress.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          util.pututrequest(api.uploadTonggan + '?feelingId=' + feeling.id + '&activityId=' + that.data.activityInfo.id, 'DELETE').then(res => {
            if (res && res.code == 200) {
              feeling = {}
              that.setData({
                item: feeling,
                fatherCommentsisEmpty: false,
                hiddenDelete: true,
              })
            }
          })
          //点击确定
        }
      },
      fail: function (ress) { }, //接口调用失败的回调函数
      complete: function (ress) { }, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  cancelTongGan: function (e) {
    var that = this
    let count = this.data.item.simul_count
    let photos = this.data.item.simul_photos
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan + '?feelingId=' + that.data.item.id, 'DELETE').then(res => {
        if (res && res.code == 200) {
          var tt = 'item.currentUserCollected'
          var ff = 'item.simul_count'
          var simul = 'item.simul_photos'
          var delId = 0
          for (var i = 0; i < photos.length; i++) {
            let oneFollow = photos[i]
            if (oneFollow.id == that.data.userInfo.id) {
              delId = i
              break
            }
          }
          photos.splice(delId, 1)

          this.setData({
            [tt]: false,
            [ff]: count - 1,
            [simul]: photos,
            hiddenDelete: true
          })
          wx.showToast({
            title: '取消同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }

  },




})